<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Manage_staffusers extends CI_Controller {
    public function index()
    {
        $data['title'] = "Manage Staff Users";
        $staffuser_response = $this->session->flashdata('staffuser_response');
        $data['data'] = array (
            "response" => $staffuser_response
                    );
        
        $data['js'] = array("manage_staffusers.js");
        
        $data['view'] = "settings/view_manage_staffusers";
        $this->load->view('view_template',$data);
    }
        
    public function searchResults(){
        extract($this->ajax->post("query","filter"));
        $this->load->model('staffusers');
        $results = array();
        $options = array();
        switch($filter){
            case 0://Full Name
                $results = $this->staffusers->getLikeName($query, $this->session->userdata('role'));
                break;
            case 1://Email
                $results = $this->staffusers->getLikeEmail($query, $this->session->userdata('role'));
                break;
            case 2://Username
                $results = $this->staffusers->getLikeUsername($query, $this->session->userdata('role'));
                break;
            default://We didn't get a good input
                return;
        }
        
        //Get data in format for view_options
        foreach($results->result() as $result){
            $options[$result->staffuser_id] = array(
                'title'=> $result->staffuser_title,
                'desc' => get_role_short($result->staffuser_role).': '.$result->staffuser_login.' - '.$result->staffuser_email
            );
        }
        
        $this->load->view('ajax/view_list',
            array(
                "options"=>$options,
                "function"=>"selectStaffuser"
            )
        );
    } 
    
    public function previewStaffuser(){
        extract($this->ajax->post("staffuser_id"));
        $this->load->model('staffusers');
        $row = $this->staffusers->getByID($staffuser_id);

        $this->load->view('ajax/view_preview_staffuser',array(
            "staffuser"=>$row,
            "self" => $staffuser_id == $this->session->userdata('user_id'),
            ));
    }
    
    public function deleteStaffuser(){
        extract($this->ajax->post("staffuser_id"));
        $this->load->model('staffusers');
        
        if ($staffuser_id == $this->session->userdata('user_id')){
            $this->session->set_flashdata('staffuser_response','Can\'t delete yourself.');
            return;
        }
        
        if ($this->staffusers->deleteStaffuser($staffuser_id, $this->session->userdata('role'))){
            $this->session->set_flashdata('staffuser_response','Delete successful.');
        }
        else{
            $this->session->set_flashdata('staffuser_response','An error occured when deleting the user.');
        }
    }
}